package servlet;


import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@WebServlet(urlPatterns = "/DeleteUserServlet.do")

public class deleteUser  extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
        // 获取要删除的用户ID
//        int userId = Integer.parseInt(request.getParameter("userId"));
        String idString = request.getParameter("id");
        if (idString != null && !idString.isEmpty()) {
            int id = Integer.parseInt(idString);
            boolean success2=delete(id);
            if(success2){
                response.sendRedirect("admin/usermanager.jsp");
            }else {
                response.sendRedirect("home/404.html");
            }

        } else {
            response.sendRedirect("home/404.html");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private boolean is_exit(int userId) {

        JDBCUtil jdbcUtil = new JDBCUtil();

        try {
            String sql = "SELECT * FROM 02_38_yangyang WHERE username = ?";
            ResultSet resultSet = jdbcUtil.prepareQuery(sql, userId);
            if (resultSet.next()) {
                return true;
            }
        }
            // 处理数据库异常
        catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtil.closeConnection(); // 关闭数据库连接
        }

       return false;
    }
    private boolean delete(int userId) {
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.getconnection(); // 获取连接对象
        try {
            String sql = "DELETE FROM `02_38_yangyang` WHERE user_id = ?";
            PreparedStatement pstmt = jdbcUtil.prepareStatement(sql);
            pstmt.setInt(1, userId);
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0; // 如果影响的行数大于0，表示删除成功
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtil.closeConnection(); // 在方法执行完成后关闭连接
        }
    }





}

